package bll

import (
	"context"
	"simcard/bll/upiot"
	"simcard/config"
	"simcard/model"
	"simcard/model/entity"
	"simcard/model/mapping"
	"simcard/store"
	"simcard/store/postgres"
	"time"
)

type simCardAgent struct {
	iSimCardAgent store.ISimCardAgent
	UPIot         *upiot.UpIotCard
}

var SimCardAgent = &simCardAgent{
	iSimCardAgent: postgres.SimCardAgent,
}

func init() {
	Register(SimCardAgent)
}

func (a *simCardAgent) init() func() {

	//a.UPIot = upiot.UPIot
	scAgent := config.Conf.SimCardAgent
	a.UPIot = upiot.NewUpIot(scAgent.UPIot.ApiKey, scAgent.UPIot.ApiSecret, scAgent.UPIot.Host)

	return func() {}
}

// Create
func (a *simCardAgent) Create(ctx context.Context, in *model.SimCardAgentCreateRequest) error {
	var (
		err error
	)
	c := buildSimCardAgent(in)
	_, err = a.iSimCardAgent.Create(ctx, c)
	return err
}

// Update
func (a *simCardAgent) Update(ctx context.Context, in *model.SimCardAgentUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	if in.Id != nil {
		dict["id"] = in.Id
	}

	if in.Name != nil {
		dict["name"] = in.Name
	}

	if in.Code != nil {
		dict["code"] = in.Code
	}

	if in.Description != nil {
		dict["description"] = in.Description
	}

	if in.Balance != nil {
		dict["balance"] = in.Balance
	}

	if in.CreatedAt != nil {
		dict["created_at"] = in.CreatedAt
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here
	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt
	return a.iSimCardAgent.Update(ctx, *in.Id, dict)
}

// Delete
func (a *simCardAgent) Delete(ctx context.Context, in *model.SimCardAgentDeleteRequest) error {
	return a.iSimCardAgent.Delete(ctx, in.Id)
}

// List
func (a *simCardAgent) List(ctx context.Context, in *model.SimCardAgentListRequest) (*model.SimCardAgentListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.SimCardAgent
		out   = &model.SimCardAgentListResponse{}
	)

	if total, list, err = a.iSimCardAgent.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = mapping.SimCardAgentsEntityToDto(list)

	return out, nil
}

// Find
func (a *simCardAgent) Find(ctx context.Context, in *model.SimCardAgentInfoRequest) (*model.SimCardAgentInfo, error) {
	var (
		err  error
		data *entity.SimCardAgent
		out  = &model.SimCardAgentInfo{}
	)

	if data, err = a.iSimCardAgent.Find(ctx, in); err != nil {
		return nil, err
	}

	out = mapping.SimCardAgentEntityToDto(data)
	return out, nil
}

// buildSimCardAgent build entity
func buildSimCardAgent(in *model.SimCardAgentCreateRequest) *entity.SimCardAgent {

	ety := &entity.SimCardAgent{}

	ety.Id = in.Id

	ety.Name = in.Name

	ety.Code = in.Code

	ety.Description = in.Description

	ety.Balance = in.Balance

	ety.CreatedAt = time.Now().Unix()

	ety.UpdatedAt = in.UpdatedAt

	return ety
}
